﻿Imports Microsoft.VisualBasic.ApplicationServices.ConsoleApplicationBase
Imports System.Net.Sockets
Imports System.Text
Imports System.Drawing
Imports System.Windows.Forms
Imports System.Windows.Forms.Form.ControlCollection
Imports System.Reflection
Imports System.ServiceProcess
Imports System.ComponentModel
Imports System.Threading

Public Class Form1
    Dim AST As RichTextBox
    Dim AST2 As RichTextBox
    Dim AST3 As RichTextBox
    Dim boolt As Boolean = False
    Private demoThread As Thread = Nothing
    Delegate Sub SetTextCallback(ByVal [text] As String)
    Delegate Sub SetTextCallback2(ByVal [text2] As String)
    Dim counter As Integer = 0
    Dim bak1 As String

    Private Sub backgroundWorker1_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        Module1.Main()
        'instance avec for
        'findu for
        ' Do not access the form's BackgroundWorker reference directly.
        ' Instead, use the reference provided by the sender parameter.
        Dim bw As BackgroundWorker = CType(sender, BackgroundWorker)

        ' Extract the argument.
        Dim arg As Integer = Fix(e.Argument)

        ' Start the time-consuming operation.
        e.Result = TimeConsumingOperation(bw, arg)

        ' If the operation was canceled by the user, 
        ' set the DoWorkEventArgs.Cancel property to true.
        If bw.CancellationPending Then
            e.Cancel = True
        End If
    End Sub
    Sub runing()
        Dim newMDIChild As New Form()
        newMDIChild.MdiParent = Me
        newMDIChild.Text = "List Des Clients"
        newMDIChild.Show()
        Dim TextBox1 As New RichTextBox()
        With TextBox1
            .Multiline = True
            .Location = New Point(64, 40)
            .TabIndex = 0
            .ReadOnly = True
            .Dock = DockStyle.Fill
            .Text = "Server Start"
            .BackColor = Color.Black
            .ForeColor = Color.White
            .Update()
        End With
        newMDIChild.Controls.Add(TextBox1)
        AST = TextBox1
    End Sub

    Sub runinginfo()
        Dim newMDIChild2 As New Form()
        newMDIChild2.MdiParent = Me
        newMDIChild2.Text = "Chat en service"
        newMDIChild2.Show()
        Dim TextBox1 As New RichTextBox()
        With TextBox1
            .Multiline = True
            .Location = New Point(64, 40)
            .TabIndex = 0
            .ReadOnly = True
            .Dock = DockStyle.Fill
            .BackColor = Color.Black
            .ForeColor = Color.White
            .Text = "Chat Server Start"
            .Update()
        End With
        newMDIChild2.Controls.Add(TextBox1)
        AST2 = TextBox1
    End Sub
    Sub runingbcast()
        Dim newMDIChild3 As New Form()
        newMDIChild3.MdiParent = Me
        newMDIChild3.Text = "Server MSG"
        newMDIChild3.Show()
        Dim TextBox1 As New RichTextBox()
        With TextBox1
            .Multiline = True
            .Location = New Point(64, 40)
            .TabIndex = 0
            .Dock = DockStyle.Fill
            .BackColor = Color.DarkSlateBlue
            .ForeColor = Color.White
            .Text = "Message"
            .Update()
        End With
        Dim strbut As New Button
        With strbut
            .TabIndex = 0
            .Dock = DockStyle.Bottom
            .Text = "Send Message"
            .Update()
        End With
        Dim strbut2 As New Button
        With strbut2
            .TabIndex = 0
            .Dock = DockStyle.Bottom
            .Text = "Send Private Message"
            .Update()
        End With
        newMDIChild3.Controls.Add(TextBox1)
        newMDIChild3.Controls.Add(strbut)
        newMDIChild3.Controls.Add(strbut2)
        AddHandler strbut.Click, AddressOf seversmsclk
        AddHandler strbut2.Click, AddressOf seversmsclk2
        AST3 = TextBox1
    End Sub

    Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
        If e.Cancelled Then
            ' The user canceled the operation.
            MessageBox.Show("Operation was canceled")
        ElseIf Not (e.Error Is Nothing) Then
            ' There was an error during the operation.
            Dim msg As String = String.Format("An error occurred: {0}", e.Error.Message)
            MessageBox.Show(msg)
        Else
            ' The operation completed normally.
            Dim msg As String = String.Format("Result = {0}", e.Result)
            MessageBox.Show(msg)
        End If
    End Sub


    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim monmax As String
        Dim monmax2 As String
        monmax = "Server" & ">> " & My.User.Name & " " & My.Computer.Clock.LocalTime
        monmax2 = "Server" & ">> " & My.User.Name & " Dialog Reports Starts"
        My.Computer.FileSystem.WriteAllText("C:\Users\Sanny\Documents\2p2p\chat_server\server\bin\Debug\SMS.txt", monmax2, False)
        My.Computer.FileSystem.WriteAllText("C:\Users\Sanny\Documents\2p2p\chat_server\server\bin\Debug\TheFile.txt", monmax, False)
    End Sub

    Private Sub EndToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EndToolStripMenuItem.Click
        Me.BackgroundWorker2.RunWorkerAsync(200)
        Me.BackgroundWorker2.RunWorkerAsync(100)
    End Sub
    Private Sub StartServerToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles StartServerToolStripMenuItem.Click
        Me.BackgroundWorker1.RunWorkerAsync(100)
        Timer1.Start()
        ToolStripProgressBar1.Maximum = 3000
        ToolStripProgressBar1.Value = Timer1.Interval
        runing()
        runinginfo()
        runingbcast()
        boolt = True
    End Sub

    Private Sub BackgroundWorker2_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker2.DoWork
    End Sub

    Private Sub BackgroundWorker2_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker2.RunWorkerCompleted
        Me.AST.LoadFile("C:\Users\Sanny\Documents\2p2p\chat_server\server\bin\Debug\TheFile.txt", RichTextBoxStreamType.PlainText)
        Me.AST2.LoadFile("C:\Users\Sanny\Documents\2p2p\chat_server\server\bin\Debug\SMS.txt", RichTextBoxStreamType.PlainText)

        If e.Cancelled Then
            ' The user canceled the operation.
            ToolStripStatusLabel2.Text = ("[BW2] Operation was canceled2")
        ElseIf Not (e.Error Is Nothing) Then
            ' There was an error during the operation.
            Dim msg As String = String.Format("[BW2] An error occurred2: {0}", e.Error.Message)
            ToolStripStatusLabel2.Text = (msg)
        Else
            ' The operation completed normally.
            Dim msg As String = String.Format("[BW2] Result2 = {0}", e.Result)
            ToolStripStatusLabel2.Text = (msg)
        End If
    End Sub

    Private Function TimeConsumingOperation(ByVal bw As BackgroundWorker, ByVal sleepPeriod2 As Integer) As Integer
        Dim result As Integer = 0
        Dim rand As New Random()

        While Not Me.BackgroundWorker1.CancellationPending
            Dim [exit] As Boolean = False

            Select Case rand.Next(3)
                ' Raise an exception.
                Case 0
                    Throw New Exception("An error condition occurred.")
                    Exit While

                    ' Sleep for the number of milliseconds
                    ' specified by the sleepPeriod parameter.
                Case 1
                    Thread.Sleep(sleepPeriod2)
                    Exit While

                    ' Exit and return normally.
                Case 2
                    result = 23
                    [exit] = True
                    Exit While

                Case Else
                    Exit While
            End Select

            If [exit] Then
                Exit While
            End If
        End While
        Return result
    End Function

    Private Function TimeConsumingOperation2(ByVal bw As BackgroundWorker, ByVal sleepPeriod2 As Integer) As Integer
        Dim result As Integer = 0
        Dim rand As New Random()

        While Not Me.BackgroundWorker2.CancellationPending
            Dim [exit] As Boolean = False

            Select Case rand.Next(3)
                ' Raise an exception.
                Case 0
                    Throw New Exception("An error condition occurred.")
                    Exit While

                    ' Sleep for the number of milliseconds
                    ' specified by the sleepPeriod parameter.
                Case 1
                    Thread.Sleep(sleepPeriod2)
                    Exit While

                    ' Exit and return normally.
                Case 2
                    result = 23
                    [exit] = True
                    Exit While

                Case Else
                    Exit While
            End Select

            If [exit] Then
                Exit While
            End If
        End While
        Return result
    End Function
    Private Sub ThreadProcUnsafe()
        Me.ToolStripProgressBar1.Value = 50
        Me.AST.Text = "This text was set unsafely."
    End Sub
    Private Sub ThreadProcSafe()
        Me.SetText("This text was set safely.")
    End Sub
    Private Sub ThreadProcSafe2()
        Me.SetText2(50)
    End Sub
    Private Sub SetText(ByVal [text] As String)

        ' InvokeRequired required compares the thread ID of the
        ' calling thread to the thread ID of the creating thread.
        ' If these threads are different, it returns true.
        If Me.AST.InvokeRequired Then
            Dim d As New SetTextCallback(AddressOf SetText)
            Me.Invoke(d, New Object() {[text]})
        Else : Me.AST.Text = [text]
        End If
    End Sub
    Private Sub SetText2(ByVal [text2] As Integer)

        ' InvokeRequired required compares the thread ID of the
        ' calling thread to the thread ID of the creating thread.
        ' If these threads are different, it returns true.
        
    End Sub

    Private Sub Timer1_Disposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Disposed
        ' MessageBox.Show("xd")
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Me.BackgroundWorker2.RunWorkerAsync(200)
        ToolStripProgressBar1.Value = 0
        ToolStripProgressBar1.Value = Timer1.Interval.ToString()
        ToolStripStatusLabel1.Text = "[TIMER] Actualisez" & " A:  " & counter + 1
        ToolStripStatusLabel3.Text = "Serveur demarrer :" & BackgroundWorker1.IsBusy
        counter = counter + 1
    End Sub

    Private Sub seversmsclk(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Module1.handleClinet.servermsg(AST3.Text)
    End Sub

    Private Sub seversmsclk2(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Module1.handleClinet.servermsgpv(AST3.Text)
    End Sub

    Private Sub Form1_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        BackgroundWorker1.WorkerSupportsCancellation = True
        BackgroundWorker1.CancelAsync()
        For Each proc In Process.GetProcessesByName("Seeme")
            proc.CloseMainWindow()
        Next
    End Sub
End Class
